import 'package:sqflite/sqflite.dart';
import '../models/app_settings.dart';
import '../services/database_service.dart';
import 'settings_repository.dart';

/// 设置数据仓库实现
/// Settings repository implementation
class SettingsRepositoryImpl implements SettingsRepository {
  final DatabaseService _databaseService = DatabaseService();

  @override
  Future<List<AppSettings>> getAllSettings() async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      'app_settings',
      orderBy: 'key ASC',
    );
    
    return List.generate(maps.length, (i) {
      return AppSettings.fromJson(maps[i]);
    });
  }

  @override
  Future<String?> getSettingValue(String key) async {
    final db = await _databaseService.database;
    final List<Map<String, dynamic>> maps = await db.query(
      'app_settings',
      columns: ['value'],
      where: 'key = ?',
      whereArgs: [key],
      limit: 1,
    );
    
    if (maps.isNotEmpty) {
      return maps.first['value'] as String;
    }
    return null;
  }

  @override
  Future<void> setSetting(String key, String value) async {
    final db = await _databaseService.database;
    final setting = AppSettings(
      key: key,
      value: value,
      updatedAt: DateTime.now(),
    );
    
    await db.insert(
      'app_settings',
      setting.toJson(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  @override
  Future<void> setSettings(Map<String, String> settings) async {
    final db = await _databaseService.database;
    final batch = db.batch();
    
    for (final entry in settings.entries) {
      final setting = AppSettings(
        key: entry.key,
        value: entry.value,
        updatedAt: DateTime.now(),
      );
      
      batch.insert(
        'app_settings',
        setting.toJson(),
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
    }
    
    await batch.commit();
  }

  @override
  Future<void> deleteSetting(String key) async {
    final db = await _databaseService.database;
    await db.delete(
      'app_settings',
      where: 'key = ?',
      whereArgs: [key],
    );
  }

  @override
  Future<void> resetToDefaults() async {
    final db = await _databaseService.database;
    
    // 清空所有设置
    // Clear all settings
    await db.delete('app_settings');
    
    // 重新插入默认设置
    // Re-insert default settings
    final defaultSettings = [
      AppSettings(
        key: SettingsKeys.themeMode,
        value: AppThemeMode.system.name,
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.notificationEnabled,
        value: 'true',
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.notificationTime,
        value: '20:00',
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.fontSize,
        value: FontSize.medium.name,
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.firstLaunch,
        value: 'false',
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.language,
        value: 'zh_CN',
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.autoBackup,
        value: 'false',
        updatedAt: DateTime.now(),
      ),
      AppSettings(
        key: SettingsKeys.reminderFrequency,
        value: ReminderFrequency.daily.name,
        updatedAt: DateTime.now(),
      ),
    ];

    final batch = db.batch();
    for (final setting in defaultSettings) {
      batch.insert('app_settings', setting.toJson());
    }
    await batch.commit();
  }

  @override
  Future<AppThemeMode> getThemeMode() async {
    final value = await getSettingValue(SettingsKeys.themeMode);
    if (value != null) {
      return AppThemeMode.values.firstWhere(
        (mode) => mode.name == value,
        orElse: () => AppThemeMode.system,
      );
    }
    return AppThemeMode.system;
  }

  @override
  Future<void> setThemeMode(AppThemeMode mode) async {
    await setSetting(SettingsKeys.themeMode, mode.name);
  }

  @override
  Future<bool> getNotificationsEnabled() async {
    final value = await getSettingValue(SettingsKeys.notificationEnabled);
    return value == 'true';
  }

  @override
  Future<void> setNotificationsEnabled(bool enabled) async {
    await setSetting(SettingsKeys.notificationEnabled, enabled.toString());
  }

  @override
  Future<String> getNotificationTime() async {
    final value = await getSettingValue(SettingsKeys.notificationTime);
    return value ?? '20:00';
  }

  @override
  Future<void> setNotificationTime(String time) async {
    await setSetting(SettingsKeys.notificationTime, time);
  }

  @override
  Future<FontSize> getFontSize() async {
    final value = await getSettingValue(SettingsKeys.fontSize);
    if (value != null) {
      return FontSize.values.firstWhere(
        (size) => size.name == value,
        orElse: () => FontSize.medium,
      );
    }
    return FontSize.medium;
  }

  @override
  Future<void> setFontSize(FontSize fontSize) async {
    await setSetting(SettingsKeys.fontSize, fontSize.name);
  }

  @override
  Future<bool> getIsFirstLaunch() async {
    final value = await getSettingValue(SettingsKeys.firstLaunch);
    return value == 'true';
  }

  @override
  Future<void> setIsFirstLaunch(bool isFirstLaunch) async {
    await setSetting(SettingsKeys.firstLaunch, isFirstLaunch.toString());
  }

  @override
  Future<String> getLanguage() async {
    final value = await getSettingValue(SettingsKeys.language);
    return value ?? 'zh_CN';
  }

  @override
  Future<void> setLanguage(String language) async {
    await setSetting(SettingsKeys.language, language);
  }

  @override
  Future<bool> getAutoBackupEnabled() async {
    final value = await getSettingValue(SettingsKeys.autoBackup);
    return value == 'true';
  }

  @override
  Future<void> setAutoBackupEnabled(bool enabled) async {
    await setSetting(SettingsKeys.autoBackup, enabled.toString());
  }

  @override
  Future<ReminderFrequency> getReminderFrequency() async {
    final value = await getSettingValue(SettingsKeys.reminderFrequency);
    if (value != null) {
      return ReminderFrequency.values.firstWhere(
        (frequency) => frequency.name == value,
        orElse: () => ReminderFrequency.daily,
      );
    }
    return ReminderFrequency.daily;
  }

  @override
  Future<void> setReminderFrequency(ReminderFrequency frequency) async {
    await setSetting(SettingsKeys.reminderFrequency, frequency.name);
  }

  @override
  Future<Map<String, String>> exportSettings() async {
    final settings = await getAllSettings();
    final Map<String, String> result = {};
    
    for (final setting in settings) {
      result[setting.key] = setting.value;
    }
    
    return result;
  }

  @override
  Future<void> importSettings(Map<String, String> settings) async {
    await setSettings(settings);
  }

  @override
  Future<String?> getSetting(String key) async {
    return await getSettingValue(key);
  }
}